import sys

import service.service as backend
import asyncio
from multiprocessing import Process, Queue, freeze_support
from turbojpeg import (
    TurboJPEG,
)
import cv2
import socketio
import platform

system = platform.system()

if system == "Darwin":  # macOS
    jpeg = TurboJPEG(r"./CloudEngine/libs/libturbojpeg.dylib")
elif system == "Windows":
    jpeg = TurboJPEG(r".\CloudEngine\libs\turbojpeg.dll")
elif system == "Linux":
    jpeg = TurboJPEG(r"/app/CloudService/CloudEngine/libs/libturbojpeg.so")


def to_jpeg(q: Queue):
    # 副进程连接 用来发数据
    sio_sub = socketio.Client()
    sio_sub.connect("http://127.0.0.1:3000", transports=["websocket"])
    while True:
        if not q.empty():
            image_array = q.get()
            image_array_rgb = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)
            ar = cv2.flip(image_array_rgb, 0)
            jpeg_data = jpeg.encode(ar)
            sio_sub.emit("jpeg_data", jpeg_data)


def handle_cache():
    # 处理缓存
    if system == "Windows":
        import os
        import shutil
        import tempfile

        temp_dir = tempfile.gettempdir()
        for item in os.listdir(temp_dir):
            if item.startswith("_MEI"):
                try:
                    shutil.rmtree(os.path.join(temp_dir, item))
                    print("删除缓存")
                except RuntimeError:
                    print("占用")
                except PermissionError:
                    print("访问临时文件夹时被拒绝，请检查权限。")


if __name__ == "__main__":
    # windows下阻止子进程重复运行
    freeze_support()
    # 创建进程间队列
    queue = Queue()
    result_queue = Queue()
    if len(sys.argv) < 2 or sys.argv[1] != "no-graphic":
        print("创建进程")
        handle_cache()
        other_process = Process(target=to_jpeg, args=(queue,))
        other_process.start()
    service: backend.Service = backend.Service(queue, result_queue, None)
    asyncio.run(service.run())
